# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.

from json import dumps

from flask import make_response, current_app
from flask.json.provider import DefaultJSONProvider
from flask_restful.utils import PY3

from ksai.serializer import serialize, JsonSerializable
from ksai.json import serialize


def json_output_response(data, code="200", headers=None):
    """Makes a Flask response with a JSON encoded body"""

    if headers is None:
        headers = {"Content-Type": "application/json"}

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 2)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    if isinstance(data, JsonSerializable):
        data = serialize(data)
    dumped = dumps(data, **settings, ensure_ascii=False) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


class ApplicationJSONProvider(DefaultJSONProvider):
    default = staticmethod(serialize)
    ensure_ascii = False
